package com.mapfinal.data.shpfile;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lambkit.common.util.FileUtils;
import com.mapfinal.data.MapLayer;
import com.mapfinal.data.MapStore;
import com.mapfinal.data.StoreManager;
import com.mapfinal.data.StoreType;

public class ShapefileStore implements MapStore {
	
	private String name;
	private List<MapLayer> layers;
	private List<String> datas;
	
	private String path;
	
	public static ShapefileStore create(String storeName, String storePath) {
		File file = new File(storePath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			return null;
		}
		ShapefileStore store = new ShapefileStore();
		store.setPath(storePath);
		store.setName(storeName);
		//遍历文件夹，加入datas
		File flist[] = file.listFiles();
		if (flist != null && flist.length > 0) {
			for (File f : flist) {
				if(!f.isFile()) continue;
				// 这里将列出所有的文件
				if(f.getName().endsWith(".shp")) {
					String name = f.getName();
					name = FileUtils.removePrefix(name, ".shp");
					store.addData(name);
				}
			}
		}
		StoreManager.me().addStore(store);
		return store;
	}
	
	@Override
	public StoreType getType() {
		// TODO Auto-generated method stub
		return StoreType.SHPFILE;
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return name;
	}

	@Override
	public void addLayer(MapLayer layer) {
		// TODO Auto-generated method stub
		if(layers==null) {
			layers = Lists.newArrayList();
		}
		layers.add(layer);
	}
	
	@Override
	public MapLayer getLayer(String name) {
		// TODO Auto-generated method stub
		if(layers!=null) {
			for (MapLayer layer : layers) {
				if(layer.getName().equalsIgnoreCase(name)) {
					return layer;
				}
			}
		}
		return null;
	}

	@Override
	public List<MapLayer> getLayers() {
		// TODO Auto-generated method stub
		return layers;
	}
	
	@Override
	public List<String> getDatas() {
		// TODO Auto-generated method stub
		return datas;
	}
	
	public void addData(String data) {
		if(datas==null) {
			datas = Lists.newArrayList();
		}
		datas.add(data);
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setLayers(List<MapLayer> layers) {
		this.layers = layers;
	}
	
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}

	public void setDatas(List<String> datas) {
		this.datas = datas;
	}

	@Override
	public void publish(String dataName, MapLayer layer) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Map<String, Object> info() {
		// TODO Auto-generated method stub
		Map<String, Object> info = Maps.newHashMap();
		info.put("name", name);
		info.put("path", path);
		return info;
	}
}
